简体   繁体   中英

Javascript field validation form

1.Okay so I want to make my Country and Sex field a required field. I tried putting the required in the html code but its still not working. I don't know if there is a java script function to validate them.

<div class="form-group">
    <label for="country"><span class="required">* </span> Country: </label>
    <select name="country" id="selCountry" class="form-control selectpicker" required>
      <option value=" " selected>Please select your country</option>

      <option value="AF">Afghanistan</option>

    </select>
  </div>

2.I want my phone number to be numerical values only and it should contain 8 digit only. The code I wrote will erase everything each time the user input a letter in the phone field , so basically it will accept only digits.But the field should accept 8 digit only or it will output an error to the user.

 function validatephone(phone) {
   var maintainplus = '';
   var numval = phone.value
   if (numval.charAt(0) == '+') {
     var maintainplus = '';
   }
   curphonevar = numval.replace(/[\\A-Za-z!"£$%^&\,*+_={};:'@#~,.Š\/<>?|`¬\]\[]/g, '');
   phone.value = maintainplus + curphonevar;
   var maintainplus = '';
   phone.focus;
 }

Can anyone show me the right way to doing this ?

Here is my jsfiddle code that I tried so far.

https://jsfiddle.net/2oong6n2/2/

1) you have already selected your option using this. so required value will always return true. whether you give country name or not .

<option value=" " selected>Please select your country</option>

try this <option value="" selected>Please select your country</option>

2) for radio button you have put required attribute in label . you have to do it in input element .

<input type="radio" name="gender" value="no" required/> Female

https://jsfiddle.net/2oong6n2/3/

  1. See this jsfiddle to allow only numbers to be entered into the text field http://jsfiddle.net/Lm2hS/

  2. Use maxlength attribute for the input field to limit the number of characters to 8 digits

 <input type="text" maxlength="8" /> 

  1. To make Gender field a required field just add checked attribute to the input field

 <input type="radio" name="gender" value="yes" checked="checked"/>Male <input type="radio" name="gender" value="no" /> Female 

  1. To make country field required use selected attribute to the option tag

 <select name="country" id="selCountry" class="form-control selectpicker" required> <option value=" " selected>Please select your country</option> <option value="AF" selected>Afghanistan</option> </select> 

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