简体   繁体   中英

Validating an integer field on a form

I have this input box in a blazor server application which should be an integer field. I want to do validation to be sure that the value entered is an integer

     <div class="mb-5">
        <input type="text" class="form-control  form-control-lg" id="numberofclasses" @bind-value="_myModel.NumberOfClasses">
     </div>

I can see a lot of code online doing something like this.

        public bool MyValidation()
        {
            bool result = true;
            int numberOfClasses = 0;
            
            if (int.TryParse(_myModel.NumberOfClasses.ToString(), out numberOfClasses))
            {
                //it is a valid integer => you could use the distance variable here
                
            }else
            {
                result = false;
            }

            return result;
        }
        

Is this a standard way of validating an integer field?

If you want a number, use the InputNumber control, or <input type="number">

Browsers, especially on phones, have their own ways of handling certain kinds of inputs, which are familiar to their users. If you try to make a custom control using a text input, then those native controls will be bypassed, which will very likely lead to someone closing the page in disgust.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM