Form Validation - javascript

JS:
validate document.forms();
if (document.forms[0].userAge.value == "") {
alert("Age field cannot be empty.");
return false;
}
if (document.forms[0].userAge.value < 5) {
alert("Your age input is not correct.");
return false;
}
if (userage == isNumber) {
alert("Your age input is not correct.");
return false;
}
alert("Name and Age are valid.");
return true;
HTML:
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" />
</div>
If this is the code I have, how would I make it so that if someone were to enter a non number in the age text box an alert would come up saying " Your input is not correct"?

Edit: I originally suggested using parseInt with isNaN() to test if the input was non-numeric. Well, it seems that using a regex is preferrable not only formatching cases like "4a" correctly, but it's actually faster in many cases (surprise!).
I mocked up some HTML with a button to illustrate.
HTML:
<form>
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" />
<input type="button" id="test" name="test" value="Test" />
</form>
JavaScript:
function validateForm() {
// get the input value once and use a variable
// this makes the rest of the code more readable
// and has a small performance benefit in retrieving
// the input value once
var userAge = document.forms[0].userAge.value;
// is it blank?
if (userAge === "") {
alert("Age field cannot be empty.")
return false;
}
// is it a valid number? testing for positive integers
if (!userAge.match(/^\d+$/)) {
alert("Your age input is not correct.")
return false;
}
// you could also test parseInt(userAge, 10) < 5
if (userAge < 5) {
alert("Your age input is not correct.")
return false;
}
alert("Name and Age are valid.");
return true;
}
// trigger validateForm() however you want, I did this as an example
document.getElementById("test").onclick = validateForm;
​Here is a jsFiddle to demonstrate: http://jsfiddle.net/willslab/m2spX/6/
About the regex: userAge.match(/^\d+$/) returns true if userAge only contains a positive integer. The beginning / and ending / indicate a regular expression literal. \d indicates ASCII digits only. + matches one or more occurrences of the previous pattern (digits in this case). ^ indicates match from the beginning, and $ indicates match until the end. So /^\d+$/ is a regex literal matching only ASCII digits from beginning to end!
Also note that you can combine the last two if statements using an OR operator (||). I left these isolated in case you want to give each one a unique validation message.
It would look like this:
if (!userAge.match(/^\d+$/) || userAge < 5) {
alert("Your age input is not correct.")
return false;
}
Feel free to ask any questions about the code and I will explain. I hope that helps!

I recommend you to use the following Javascript which will not allow non-numeric characters in the text field.
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
return true;
}
<input type="text" id="userAge" name="userAge" onkeypress="return isNumberKey(event);">

Try this solution
<script language="javascript">
function validate(){
alert("validate ..."+document.forms[0].userAge.value);
if (document.forms[0].userAge.value == ""){
alert("Age field cannot be empty.");
return false;
}
if (document.forms[0].userAge.value<5){
alert("Your age input is not correct.");
return false;
}
//provide a way to validate if its numeric number..maybe using regexp
//if (isNumeric(userAge)){
// alert("Your age input is not correct.");
// return false;
//}
//alert"Name and Age are valid."
return true;
}
</script>
The HTML should be
<form>
<div><label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge" onblur="validate()"/>
</div>
</form>

use the code below
if(isNaN(document.forms[0].userAge.value)){
alert('This is not a number');
}

Related

Determining if a user input field is empty

I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.
function Script() {
var G = document.getElementById("gradevalue").value
if (G == null || G == undefined) {
window.alert("Please input a grade");
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="text"; size="2"; maxlength="2">
</label>
<input type="button" value="GRADE!" id="nota" onclick="Script()">
I'm very new at this, so please don't be too harsh.
I think, you can simply check it like:
if (!Number(G)) {
window.alert("Please input a grade");
}
this is going to be true if G is null, undefined, '', 0, false and NaN and any strings that are not converted to numbers.
function CheckGrade () {
var G = document.getElementById("gradevalue").value;
if(!Number(G)) {
window.alert("Please input a grade");
} else {
//your code here, maybe some othe validation logic
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="number" min="1" max="10"/>
</label>
<input type="button" value="GRADE!" id="nota" onclick="CheckGrade()">
UPDATE Added a code sample and minor mistakes.
Checking !G || G == 0 seems to do the job:
function Script() {
var G = document.getElementById("gradevalue").value
if(!G || G == 0) {
window.alert("Please input a grade");
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="text"; size="2"; maxlength="2">
</label>
<input type="button" value="GRADE!" id="nota" onclick="Script()">
Note that you may also want to check for > 11 values:
if (!G) {
window.alert("Please input a grade");
} else if(G == 0 || G > 10) {
window.alert("Please input a grade between 1 and 10");
}
You are also must there, in JavaScript you can just check if the variable has a value assigned to it, if it doesn't then the bool expression will be false. I have done a quick CodePen with the working code https://codepen.io/robdavis/pen/bRVxdm
function Script() {
var g = document.getElementById("gradevalue").value
if (!g) {
window.alert("Please enter a Grade");
}
}

Getting function to run as user types

I have a phone number input that I am trying to get the dashes to appear in the number as the user types.
I am wanting the number to appear as 555-555-5555.
The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.
Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?
$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>
I modified your code slightly to produce something that I think is a little easier to read, but still does the job.
I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:
--UPDATE--
After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:
First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.
I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.
let formatFlag = false;
$(function(){
$('#phone').keyup(function(evt) {
let modifiedValue = $(this).val().replace(/-/g, "");
if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {
//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {
formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
} else {
return false; //Hyphen already present, no formatting necessary
}
} else {
formatFlag = false;
}
return false; //Return if backspace or delete is pressed to avoid awkward formatting
}
if(!!formatFlag) {
// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));
formatFlag = false; //Reset the formatFlag
}
if(modifiedValue.length % 3 == 0) {
if(modifiedValue.length === 0 || modifiedValue.length >= 9){
return false;
} else {
$(this).val($(this).val() + '-');
return;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>

Combining these two functions into one

Hey guys I have a password validator that I amd having issues working on, its quite lengthy and I think can be shortened down and simplified if possible.
Could someone assist me in simplifying it. Im talking about the checkValidPassword() function.
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
// check the length of the password
checkValidPassword(input);
}
}
function checkValidPassword(input) {
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm password');
if (password.value.length < 8) {
password.setCustomValidity('Password must contain at least 8 characters!');
} else {
var re = /[0-9]/;
if (!re.test(password.value)) {
password.setCustomValidity('password must contain at least one number (0-9)!');
} else {
password.setCustomValidity("");
}
}
}
And im trying to implement a way for the user to must include atleast a number also. I was thinking about
str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
Would I include that in the if statment with $$ to symbolize and also check characters ?
if(password.value.length < 8 && str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)) {
This is essentially a code review question, but ok... I'd rewrite your function to something like:
function checkPassword() {
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm password');
if (password.value != confirm_password.value) {
password.setCustomValidity('Password Must be Matching.');
return false;
}
if(password.value.length < 8 ) {
password.setCustomValidity('Password must contain at least 8 characters!');
return false;
}
if(!/[0-9]/.test(password.value)) {
password.setCustomValidity('password must contain at least one number (0-9)!');
return false;
}
return true;
}
Basically, check each condition individually and return immediately if it fails, thus avoiding extra indentation ("early exits"). This is a bit verbose, but far more readable than a monster regular expression, especially if you don't know for sure what it does.
I managed to figure it out, I combined them both by just putting the else into one another.
function ValidatePassword(pass, confirm_pass) {
if (pass.value != confirm_pass.value || pass.value == "" || confirm_pass.value == "") {
confirm_pass.setCustomValidity("the Passwords do not match");
pass.setCustomValidity("the Passwords do not match");
} else {
if(pass.value.match(/(?=^.{8,30}$)([a-zA-Z]+[0-9])$/)) {
pass.setCustomValidity("");
confirm_pass.setCustomValidity("");
} else {
pass.setCustomValidity("the password doesnt have numbers");
confirm_pass.setCustomValidity("the password doesnt have numbers");
}
}
}
Here is what I made the form look like:
<form>
password
<input id="pass" type="password" required="" placeholder="Password" />
<br> confirm
<input id="confirm_pass" type="password" required="" placeholder="confirm" onfocus="ValidatePassword(document.getElementById('pass'), this);" oninput="ValidatePassword(document.getElementById('pass'), this);" />
<br> username :
<input id="username" required="" type="text">
<br>
<button class="btnform" name="register" type="submit">Complete Registration</button>
</form>

How to check value length with using Javascript?

Hello everyone I would like to ask how to check value's length from textbox ?
Here is my code :
#*<script>
function validateForm() {
var x = document.forms["frm"]["txtCardNumber"].value;
if (x == null || x == "" ) {
alert("First name must be filled out");
return false;
}
}
</script>*#
When I run my script yeap I got alert message but I'm trying to add property which control the texbox' input length.
You could use x.length to get the length of the string:
if (x.length < 5) {
alert('please enter at least 5 characters');
return false;
}
Also I would recommend you using the document.getElementById method instead of document.forms["frm"]["txtCardNumber"].
So if you have an input field:
<input type="text" id="txtCardNumber" name="txtCardNumber" />
you could retrieve its value from the id:
var x = document.getElementById['txtCardNumber'].value;
Still more better script would be:
<input type="text" name="txtCardNumber" id="txtCardNumber" />
And in the script:
if (document.getElementById(txtCardNumber).value.length < 5) {
alert('please enter at least 5 characters');
return false;
}

Javascript validate two textbox

The code below validate two nameserver textbox. As you can see there is redundancy in the javascript code. // validate textbox 1 and // validate textbox 2. Is there anyway I could just use one script.. you know I just want to use 1 validation function to validate two textbox. I'm sorry for my English I hope you all can understand me. Thank you.
<script type="text/javascript">
// validate textbox 1
function validate_domain(){
var nameserver1 = document.getElementById('nameserver1').value;
var domain_array = nameserver1.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver1').focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver1').focus();
return false;
}
}
// validate textbox 2
function validate_domain(){
var nameserver1 = document.getElementById('nameserver1').value;
var domain_array = nameserver2.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver2').focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver2').focus();
return false;
}
}
</script>
<fieldset class="inlineLabels">
<label for="name">Nameserver 1</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="nameserver1" name="nameserver1">
<label for="data">Nameserver 2</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="data" name="nameserver2">
</fieldset>
<button onclick="validate_domain(); submitForm('page1','directpage.php');" value="Validate" name="btn_validate" type="button" class="positive iconstxt icoPositive"><span>Save</span></button>
Well here is another approach:
function ValidateDomain(){
function CheckForBlank(domain, textBox){
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver1').focus();
return false;
}
}
function CheckForFormat(domain, textBox){
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver1').focus();
return false;
}
}
function GetDomainName(inputId){
var serverName = document.getElementById(inputId).value,
domain_array = serverName.split('.');
return domain_array[0];
}
var nameserver1 = GetDomainName('nameserver1'),
nameserver2 = GetDomainName('nameserver2'),
nameServerInput1 = document.getElementsById('nameserver1');
nameServerInput2 = document.getElementsById('nameserver2');
if (CheckForFormat(nameserver1,nameServerInput1) && CheckForBlank(nameserver1,nameServerInput1)
&& CheckForFormat(nameserver2,nameServerInput2) && CheckForBlank(nameserver2,nameServerInput2)){
//This means you are valid
return {
name1:nameserver1,
name2:nameserver2
}
}
return false;
}
Maybe like this:
<script type="text/javascript">
function validate_domain(){
validateTextBox('nameserver1');
validateTextBox('nameserver2');
}
function validateTextBox(tbName){
var nameserver1 = document.getElementById(tbName).value;
var domain_array = nameserver1.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById(tbName).focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById(tbName).focus();
return false;
}
}
}
</script>
Saw this one at work. Played with it at home. Here's a working jsFiddle. Yes, it's overly complex, but I detest alert('annoying pop-up');.
I commented the source, so you would better understand why I wrote it like that.
sg522: It may not copy/paste into your code and work, but I don't know what the rest of your code is. Neither are we here to write your code for you. We are here to help you learn and become a more experienced programmer.
Please let us know if you have questions.
Happy coding!
UPDATE: Modified jsFiddle to work with Opera and Firefox 10.
Neither Opera or Firefox apparently allow cloneNode to be called without parameters now.
Opera also apparently does not allow chained variable declarations.
Take the id of the element you want to validate as a parameter of your function.
// validate textbox
function validate_domain(serverName){
var server = document.getElementById(serverName).value;
var domain_array = server.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById(serverName).focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById(serverName).focus();
return false;
}
}
<script type="text/javascript">
// validate textbox
function validate_domain(ele){
var nameserver = ele.value;
var domain_array = nameserver.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
ele.focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
ele.focus();
return false;
}
}
</script>
<fieldset class="inlineLabels">
<label for="name">Nameserver 1</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="nameserver1" name="nameserver1">
<label for="data">Nameserver 2</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="data" name="nameserver2">
</fieldset>
<button onclick="validate_domain(document.getElementById('nameserver1')); validate_domain(document.getElementById('nameserver2')); submitForm('page1','directpage.php');" value="Validate" name="btn_validate" type="button" class="positive iconstxt icoPositive"><span>Save</span></button>

Categories