Stefano Tokyo Stefano Tokyo - 2 months ago 23
Javascript Question

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>


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 = '';

Can anyone show me the right way to doing this ?

Here is my jsfiddle code that I tried so far.


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