javascript validation numerical - javascript

Hi sorry i'm still pretty new to javascript.
I've developed a form in HTML and now i'm attempting to add javascript to validate the form.
So far i have simple javascript to make sure each element is filled in,
if (document.order.suburb.value=="")
{
alert("Suburb Cannot Be Empty")
return false
}
if (document.order.postcode.value=="")
{
alert("Postcode Cannot Be Empty")
return false
}
I then have javascript to validate the length of some of the elements,
if (document.order.telephone.value.length < 10)
{
alert("Invalid Telephone Number")
return false
}
Now i'm trying to validate numeric values in the telephone number part but it's not executing correctly, it's like the code is just ignored when it's being executed.
var digits="0123456789"
var temp
var i
for (i = 0 ; i <document.order.telephone.value.length; i++)
{
temp=document.order.telephone.value.substring(i,i+1)
if (digits.indexOf(temp)==-1)
{
alert("Invalid Telephone Number")
return false
}
}
Thanks for reading and thanks for the help :) been stuck on this issue for weeks and have no idea what i'm doing wrong, i tried to code on a separate document with another form and it seemed to work fine.
EDIT
Code for validation for digits in postcode
var post = document.order.postcode.value.replace(white,'');
if(!post){
alert("Post code required !");
return false;
}
post = post.replace(/[^0-9]/g,'');//replace all other than digits
if(!post || 4 > postcode.length) {
alert("Invalid Postcode !");
return false;
}

You may try this example:
var validate = function() {
var white = /\s+/g;//for handling white spaces
var nonDigit = /[^0-9]/g; //for non digits
if(!document.order.suburb.value.replace(white, '')) {
alert("Suburb required !");
return false; //don't allow to submit
}
var post = document.order.postcode.value.replace(white, '')
if(!post) {
alert("Post code required !");
return false;
}
post = post.replace(nonDigit,'');//replace all other than digits
if(!post || 6 > post.length) { //min post code length
alert("Invalid Post code !");
return false;
}
var tel = document.order.telephone.value.replace(white, '');
if(!tel) {
alert("Telephone required !");
return false;
}
tel = tel.replace(nonDigit,'');
if(!tel || 10 > tel.length) {
alert("Invalid Telephone !");
return false;
}
return true; //return true, when above validations have passed
};
<form onsubmit="return validate();" action="#" name="order">
Suburb: <input type="text" id="suburb" name="suburb" ><br/>
Post code: <input type="text" id="postcode" name="postcode"/><br/>
Telephone: <input type="text" id="telephone" name="telephone"/><br/>
<input type="reset"/><input type="submit"/>
</form>

Here is a FIDDLE that will give you something to think about.
You could handle this task in hundreds of ways. I've just used a regex and replaced all of the non-numbers with '' - and compared the length of two variables - if there is anything other than a number the length of the regex variable will be shorter than the unchanged mytelephone.
You can do all kinds of "validation" - just me very specific in how you define "valid".
JS
var mysuburb, mypostcode, mytelephone;
$('.clickme').on('click', function(){
mysuburb = $('.suburb').val();
mypostcode = $('.postcode').val();
mytelephone = $('.telephone').val();
console.log(mysuburb + '--' + mypostcode + '--' + mytelephone);
if(mysuburb.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('Suburb is required');
return false;
}
if(mypostcode.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('postode is required');
return false;
}
if( mytelephone.length < 1 )
{
$('.errorcode').html('');
$('.errorcode').append('telephone number is required');
return false;
}
if( mytelephone.length != mytelephone.replace(/[^0-9]/g, '').length)
{
$('.errorcode').html('');
$('.errorcode').append('telephone number must contain only numbers');
return false;
}
});

Related

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

Try to validate IP Address with javascript

I'm a beginner to javascript. Now, I'm trying to make a form to post back to server. There are some "input" that contains ip address which should be validate before submitting. Now I have done a javascript function which work well. But now I'm trying to add this function into jquery selection. Just confuse how to do it.
This is my validate javascript code.
function ValidateIPaddress(Ipfield)
{
IpAddr=Ipfield.value;
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(!IpAddr.match(ipformat))
return true;
else
return false;
}
and this is now how I implement for this validation.
<input type= "text" name= "LocalIP" style= "margin-right:10px " value="192.168.1.193" class="ip" onfocusout="ValidateIPaddress(document.getElementById('LocalIp'))" id="LocalIp" > Remote VIP Address :
<input type= "text" name= "RemoteVIPAddr" style= "margin-right:10px" value="234.5.6.7" class="ip" onfocusout="ValidateIPaddress(document.getElementById('RemoteIp'))" id="RemoteIp" >
Remote VIP Port :
<input type= "text" name= "RemoteVIPPort" style= "margin-right:10px" value="5004" class="ip" onfocusout="ValidatePort(document.getElementById('RemoteVIPPort'))" id="RemoteVIPPort">
Now I want to use jquery selection to always check if there are some invalid input. Which is something like this but with my own design function.
$("input.ip:visible").filter(function() { return this.ValidateIPaddress === true }).addClass("invalid");
Anyone has idea bout it?
You're not calling ValidateIPAddress in your filter function, you're just testing whether the DOM element has a non-empty property named ValidateIPAddress. It should be:
$("input.ip:visible").filter(function() {
return ValidateIPAddress(this);
}).addClass("invalid");
Try this:
isIP(ip) {
if (typeof(ip) !== 'string')
return false;
if (!ip.match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)) {
return false;
}
return ip.split('.').filter(octect => octect >= 0 && octect <= 255).length === 4;
}
Original: https://stackoverflow.com/a/50612630/3261332
And if one needs to accept also CIDR format IP/{0-32} please update the 2 lines as below:
if (!ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/([0-9]|[12][0-9]|3[0-2]))?$/)) {
return ip.split('/')[0].split('.').filter(octet => octet >= 0 && octet <= 255).length === 4;
See if this help. This is valid fo IP4 only.
0.0.0.0 - Invalid
Any ip with CIDR is invalid
function validateIP(ip) {
is_valid = false;
ip = ip.replace(/\s+/, "");
if(ip.indexOf('/')!=-1){
alert("IP not valid");
return false
}
try {
var ipb = ip.split('.');
if (ipb.length == 4) {
for (i = 0; i < ipb.length; i++) {
b = parseInt(ipb[i]);
if (b >= 0 && b <= 255) {
is_valid = true;
} else {
is_valid = false;
break;
}
}
}
} catch (exception) {
alert("IP is not valid")
return false;
}
if (!is_valid) {
alert("IP is not valid")
return false;
}
return true;
}

Check the length of the number entered in a textbox

I want to write in text box and check if is integer and less than 16 numbers. I have the following JavaScript codes.
<script type="text/javascript">
function doCheck(field) {
if (isNaN(document.getElementById(field).value)) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else {
return true;
}
}
</script>
<form method="post" action="" onsubmit="return doCheck('number');">
national id=<input type="text" name="nat" id="number">
<input type="submit" name="submit">
</form>
document.getElementById(field).value.length
you can find the length of string inside the text box using this
function doCheck(field) {
var len = document.getElementById("number").val().length;
if(parse.Int(document.getElementById(field).value) && len < 16) {
return true;
}
else {
alert('your alert');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
}
be sure you parse it as an integer.
function doCheck(field) {
var input_value = document.getElementById(field).value;
if(isNaN(input_value) || parseInt(input_value,10) != input_value || input_value.length < 16) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else{
return true;
}
}
isNAN() checks whether a number is an illegal number of any type, not only integer. So you have to use something else there, a regular expressions maybe.
To get the length of the field you can simply use:
document.getElementById(field).value.length

Minimum character count text box

my code isn't working for some reason..here it is:
html:
<input type="text" name="post" maxlength="140" />
and for javascript:
var inpt = document.getElementsByName("post")[0];
// var inputValue=document.getElementById(post).value;
if (inpt.value < 10) {
return false;
alert("Post must be longer than 10 characters.");
} else {
return true;
}
i tried it with and without quoting the second line and both do nothing. also i made sure to change inpt.value to inputValue.length when i unquoted the second line.
There are 2 problems
var inpt = document.getElementsByName("post")[0];
//need to test the length
if (inpt.value.length < 10) {
alert("Post must be longer than 10 characters.");
//return after the alert
return false;
} else {
return true;
}
Also make sure that the script is triggered on an event
function validate() {
var inpt = document.getElementsByName("post")[0];
//need to test the length
if (inpt.value.length < 10) {
alert("Post must be longer than 10 characters.");
//return after the alert
return false;
} else {
return true;
}
}
<form onsubmit="return validate()">
<input type="text" name="post" maxlength="140" />
<button>Save</button>
</form>
Put the alert before the return statement.

form still submitted after return false javascript

I'm having a little problem with a validation thing in javascript.
<form action="insert.php" id="form" name="form" method="post"
onSubmit="return validate()">
<pre>
Vul hier de/het E-mail adres(sen) in
<textarea name="email" rows="5" cols="50"></textarea><br>
Typ hier de E-mail
<textarea name="text" rows="5" cols="50"></textarea><br>
<input type="submit" name="Submit" value="Submit">
</pre>
</form>
As you can see here, I've got two textareas. In the upper one, you're supposed to enter one or multiple email addresses underneath eachother, and in the bottom textarea you're supposed to compose the email itself. Then, when you click on submit, it'll send the email to all those specified email addresses.
Now, I've made a validation for both textareas:
function explodeArray(emailID, delimiter) {
tempArray = new Array(1);
var Count = 0;
var tempString = new String(emailID);
while (tempString.indexOf(delimiter) > 0) {
tempArray[Count] = tempString.substr(0, tempString.indexOf(delimiter));
tempString = tempString.substr(
tempString.indexOf(delimiter) + 1,
tempString.length - tempString.indexOf(delimiter) + 1
);
Count = Count + 1
}
tempArray[Count] = tempString.replace("\r", "");
return tempArray;
}
function validate() {
var emailID = document.form.email;
var delimiter = "\n";
var emailArray = explodeArray(emailID.value, delimiter);
var textID = document.form.text;
var length = emailArray.length,
element = null;
for (var i = 0; i < length; i++) {
emailVar = emailArray[i];
if (emailVar == null) {
alert("Email-adres bestaat niet")
emailID.focus()
return false
}
if (emailVar == "") {
alert("Email-adres veld is leeg")
emailID.focus()
return false
}
if (checkEmail(emailVar) == false) {
emailVar.value = ""
alert("Ongeldig E-mail adres");
emailVar.focus()
return false
}
}
if ((textID.value == null) || (textID.value == "")) {
alert("E-mail textveld is leeg")
textID.focus()
return false
}
document.getElementById("form").submit();
return true
}
function checkEmail(hallo) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(hallo)) {
return true
}
return false
}
(I probably copied lots of irrelevant code as well, sorry for that, just copied the whole thing just in case...)
Now what does work is:
-it won't submit when both textareas are empty;
-it won't submit when the email addresses are valid but the bottom textarea is empty;
What doesn't work is:
-the form still submits when the email addresses are invalid, even when the bottom textarea is still empty.
I've been trying to figure out for hours what could possibly be wrong here, I googled and checked stackoverflow, but I really could not find anything. Could anybody tell me what I'm doing wrong here?
Thanks in advance.
You were using emailVar.focus(); which won't execute.
Here, fixed: Live Demo
if (checkEmail(emailVar) == false) {
alert("Ongeldig E-mail adres");
emailID.focus();
return false;
}

Categories

Resources