Stop form whitespace when user pressing submit - javascript

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;
}
}

Related

How to prevent characters being submitted with form input

I'm in the process of creating a gambling website, but currently with the betting form input you can type a negative number etc (-100) and you will have 100 coins put into your balance.
I need to restrict the use of anything but number digits being used within the input. Currently my work around is blocking the user from typing in anything other than numbers but you are able to hop into the developer tools and insert the value manually.
I believe i need to have an onSubmit validation for the input which says if anything but numbers are inserted do not allow the submit.
I'm not sure how i will do this, thanks for the help!
put onkeypress="return onKeyValidate(event,alpha);" on your input box,and
call the function
function onKeyValidate(e,charVal){
var keynum;
var keyChars = /[\x00\x08]/;
var validChars = new RegExp(charVal);
if(window.event)
{
keynum = e.keyCode;
}
else if(e.which)
{
keynum = e.which;
}
var keychar = String.fromCharCode(keynum);
if (!validChars.test(keychar) && !keyChars.test(keychar))
{
return false
} else{
return keychar;
}
}
Use ctype_digit()
//returns true
<?php
if (ctype_digit('123')) {
echo 'true';
} else {
echo 'false' ;
}
?>
//returns false
<?php
if (ctype_digit('-123')) {
echo 'true';
} else {
echo 'false' ;
}
?>
you can use this reguler expression to validate for numbers
samp html <button type="submit" onclick="myfunc()">Click Me!</button>
function myfunc(){
var a = /^\d*$/;
{
if(!a.test(value of input))
{
alert('Please provide a Number');
return false;
}
}
}
here
/ at both ends mark the start and end of the regex
^ and $ at the ends is to check the full string than for partial matches
d* looks for multiple occurrences of number charcters
if you want only positive numbers use this/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/
this jquery code can solve your problem
$(function(){
$("#submit").click(function(evnt){
var inptTxt = $("#myField").val();
if(check(inptTxt)){
//your test true then submits
$('#form').submit;
}else{ //test failed
evnt.preventDefault();
}
})
})
here the #submit is the id of submit button and #form is the id of the form to be submitted

Javascript show validation message right after the text box

I am trying to validate a form using javascript. On button click function I have called a javascript function where I have displayed the message after the text box. The number of times I click the button same number of times message gets displayed just below the existing validation message. Please help me
Here goes my code:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstname').after('Validation message');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastname').after('Some validation text');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}
Assuming I understand what v is for. Which i probably don't because v (I hate one letter variable names...).
Try this:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
if ($('#firstnameMessage').length <= 0)
{
$('#firstname').after('<p id="firstnameMessage">Validation message</p>');
document.getElementById('firstname').style.borderColor='#DA394B';
}
v = false;
}
if ((document.getElementById('lastname').value == "")) {
if ($('#lastnameMessage').length <= 0)
{
$('#lastname').after('<p id="lastnameMessage">Some validation text</p>');
document.getElementById('lastname').style.borderColor = '#DA394B';
}
v = false;
}
return v;
}
Simple fiddle to show this working: https://jsfiddle.net/srLt7wo0/
Using .after will insert another element per http://api.jquery.com/after/
The below solution uses a separate element already in the HTML to display the error message. If you use .after you have to check that you have not already added an element to your HTML
HTML
<input id="firstname" type="text"/><div id="firstnameMessage"></div>
<input id="lastname" type="text"/><div id="lastnameMessage"></div>
JS
function check() {
$("#firstnameMessage,#lastnameMessage").text(''); // clear message, reset border color
document.getElementById('firstname').style.borderColor='';
document.getElementById('lastname').style.borderColor='';
var isValid = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstnameMessage').text('First name is required');
document.getElementById('firstname').style.borderColor='#DA394B';
isValid = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastnameMessage').text('Last name is required');
document.getElementById('lastname').style.borderColor='#DA394B';
isValid = false;
}
return isValid;
}
I'm not sure to have understood you issue but maybe this could help you :)
window.firstname = document.getElementById('firstname')
window.lastname = document.getElementById('lastname')
window.issue = document.getElementById('issue')
function check() {
if(firstname.value == '' || lastname.value == '') {
issue.innerHTML = 'Please, use correct credentials.'
} else {
issue.innerHTML = ''
}
}
<input id="firstname" />
<input id="lastname" />
<button onclick="check()">
Check
</button>
<div id="issue" style="color:red;"></div>
This should work if i understand you.
It will add only one message no matter how many times you click
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#message').remove()
$('#firstname').after('<span id='message'>Validation message</span>');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#message').remove()
$('#lastname').after('<span id='message'>Some validation text</span>');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}

How to allow only numbers between 0 to 30 or A,D character in input using javascript?

Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.

javascript validation numerical

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;
}
});

Javascript validation not working?

What's wrong in it why it's not working...
<script language="JavaScript" type="text/javascript">
//function to check empty fields
function isEmpty(strfield1, strfield2) {
//change "field1, field2 and field3" to your field names
strfield1 = document.forms[0].name.value
strfield2 = document.forms[0].email.value
//name field
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
alert( "Name is a mandatory field.\nPlease amend and retry.")
return false;
}
//EMAIL field
if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
alert(" Email is a mandatory field.\nPlease amend and retry.")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(strEmail){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms[0].email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1) {
alert('A valid e-mail address is required.\nPlease amend and retry');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
return false;
}
</script>
It doesn't do anything I don't understand what's going there and in form I put this too
<form onsubmit="return check(this);" action="sendquery.php" name="contquery">
First glance: too many brackets as shown by #FishBasketGordo so I will not repeat
Second glance - you pass the field and do not test the field value
Third glance: You do not pass the correct names to the function
Fourth glance - isEmpty returns false when empty. It should return true
I fixed all those
DEMO HERE
Complete page to show where what goes. Updated to do unobtrusive event handling on the form
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
// trim for IE
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
//function to check empty fields
function isEmpty(objfld) {
var val = objfld.value;
if (val.trim() == "" || val == null) {
alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
objfld.focus();
return true;
}
return false;
}
//function to check valid email address
function isValidEmail(objEmail){
var validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
var strEmail = objEmail.value;
if (strEmail.match(validRegExp)) return true;
alert('A valid e-mail address is required.\nPlease amend and retry');
objEmail.focus();
return false;
}
//function that performs all functions, defined in the onsubmit event handler
function validate(form) {
if (isEmpty(form.name)) return false;
if (isEmpty(form.email)) return false;
return isValidEmail(form.email);
}
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
return validate(this);
}
}
</head>
<body>
<form id="form1">
Name:<input type="text" name="name" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" />
</form>
</body>
</html>
Probably the main reason it isn't working is the syntax errors:
// Syntax error ----v
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
// The return statement should be above the previous closing bracket
// and the final closing bracket removed.
return false;
}
There's an extra closing paren on the first line, and there are too many closing brackets. If you open up this up in FireBug or Chrome Developer Tools or a similar tool, it would tell you about this automatically.

Categories

Resources