i have javascript that validate every user input and only allow character to be inputed in input text.
my issue is im using input text with no submit button (search form). my javascript doesn't allow hotkey enter, here my code :
function getkey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function angkadanhuruf(e, goods, field)
{
var angka, karakterangka;
angka = getkey(e);
if (angka == null) return true;
karakterangka = String.fromCharCode(angka);
karakterangka = karakterangka.toLowerCase();
goods = goods.toLowerCase();
// check goodkeys
if (goods.indexOf(karakterangka) != -1)
return true;
// control angka
if ( angka==null || angka==0 || angka==8 || angka==9 || angka==27 )
return true;
if (angka == 13) {
var i;
for (i = 0; i < field.form.elements.length; i++)
if (field == field.form.elements[i])
break;
i = (i + 1) % field.form.elements.length;
field.form.elements[i].focus();
return false;
};
// else return false
return false;
}
<div class="search-box" style="margin-top: 20px;">
<form method="POST" id="searchform" action="search.html" >
<input name="kata" type="text" placeholder=" " onKeyPress="return angkadanhuruf(event,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#.-_',this)"/>
</form>
</div>
Related
i have this javascript code which has a function that calls other functions. The problem is the input.html form is getting submitted even if the fields are empty.. if I dont provide any input in the fields, the error messages are being shown but at the same time form gets submitted. there are numerous questions like this available but none is helping as they are not calling function within the function.. what can be the possible solution for this?
function blankos() {
var p = document.getElementById("windows");
var q = document.getElementById("linux");
if ((p.checked == false) && (q.checked == false)) {
document.getElementById("enteros").innerHTML = "Select an option";
return false;
} else if ((p.checked == true) || (q.checked == true)) {
document.getElementById("enteros").innerHTML = "";
return true;
}
}
function blankfreq() {
var r = document.getElementById("biannual");
var s = document.getElementById("monthly");
if ((r.checked == false) && (s.checked == false)) {
document.getElementById("enterfreq").innerHTML = "Select an option";
return false;
} else if ((r.checked == true) || (s.checked == true)) {
document.getElementById("enterfreq").innerHTML = "";
return true;
}
}
function blankhour() {
var i = document.getElementById("one");
var ii = document.getElementById("two");
var iii = document.getElementById("four");
if ((i.checked == true) || (ii.checked == true) || (iii.checked == true)) {
document.getElementById("enterhour").innerHTML = "";
return true;
}
return false;
}
function blank() {
blankos();
blankfreq();
blankhour();
checkselect();
}
<form onSubmit="return blank()" name="input" id="input" method="post" action="cgi-bin/review.cgi" >
blank() doesn't return anything. Try:
function blank() {
return blankos() && blankfreq() && blankhour() && checkselect();
}
This will only report the first error that's detected. If you want all of them to be reported, assign them to variables first.
function blank() {
var ok1 = blankos();
var ok2 = blankfreq();
var ok3 = blankhour();
var ok4 = checkselect();
return ok1 && ok2 && ok3 && ok4;
}
I haven't looked at all the individual validation functions, though. You probably have bugs there that need to be fixed as well.
You can use preventDefault() to restrict your form from submitting. Change your HTML from
<form onSubmit="return blank()" name="input" id="input" method="post" action="cgi-bin/review.cgi" >
to
<form name="input" id="input" method="post" action="cgi-bin/review.cgi" >
Then add this block of code
//id of the form is 'input'
$("#input").submit(function(e){
//if any of the inner functions return false then prevent from form submit
if( !blankos() || !blankfreq() || !blankhour() || !checkselect()){
e.preventDefault();
return false;
}
});
I have used below code to get value from textarea and I am not able to get it.
Given is the code for the textarea which is dynamic:
<form name="myForm">
<textarea name="fname" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
</form>
Given is my function to get value from textarea box:
function ValidateData() {
if ($("textarea").is(":visible")) {
//var x = document.forms["myForm"]["fname"].value;
var x = document.getElementsByName("fname").value;
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
You can use this code for get textarea:
function ValidateData() {
if ($("textarea").is(":visible")) {
var x = $("textarea").val();
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
How can I restrict entering special characters in the text box (txt_edition) by editing below code for validation? I want only numbers to be entered.
<script>
function validateForm()
{
var x = document.forms["frm_bokAdd"]["txt_edition"].value;
if (x==null || x=="")
{
alert("Edition must be filled out");
return false;
}
</script>
Below is my form
<form name="frm_bokAdd" action ="#" method="post" onsubmit="return validateForm()" >
<table border="0" align="center">
<tr><td> <input type="text" name="txt_edition" ></td></tr>
<tr><td> <input type="submit" name="bookIns_submit" value="Add"></td></tr>
</table>
</form>
can use this
HTML
<input type="text" onkeypress="return isNumber(event)" >
JS(at end of Body )
function isNumber(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
DEMO is Here
How can I restrict entering special characters in the text box (txt_edition)
Don't. Allow users to arrive at a valid value any way they like, you really only care that the value is valid when it's sent to the server, and even then you should validate there too.
by editing below code for validation? I want only numbers to be entered.
Just test when the form is submitted, passing a reference to the form in the call:
<form ... onsubmit="return validateForm(this)" >
and the function:
function validateForm(form) {
var value = form.txt_edition.value;
if (/\D/.test(value) || value == '') {
alert("Edition must be filled out and contain only numbers");
return false;
}
}
use regex.
if (x.match(/^[0-9]*\.[0-9]*$/) !== null) {
//text is only numbers (use /^[0-9]*$/ for integers)
}
Try it
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
body
{
font-size: 9pt;
font-family: Arial;
}
</style>
</head>
<body>
Alphanumeric value:
<input type="text" id="text1" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;"
onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Special Characters not allowed</span>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsAlphaNumeric(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>
</body>
</html>
Try to use regular expression -
var edition = document.getElementById('txt_edition').value;
outputVal = edition.replace(/[^0-9a-zA-Z]/g,"");
if (edition != outputVal) {
return false;
}
You can restrict the key press like below,
function restrict_letters(e) {
var keyCode = e . keyCode == 0 ? e . charCode : e . keyCode;
// only 0 to 9
if (keyCode < 48 && keyCode > 57) {
return false;
}
}
you can get more key codes in here.
Also change the html function call like below,
<input type="text" onkeypress="return restrict_letters(event)">
Note: function call need to give for the input field not for the form submit.
To allow user to enter only number and dot. Use this regular expression
function NumAndTwoDecimals(event , obj){
reg = /[^0-9.,]/g;
obj.value = obj.value.replace(reg,"");
}
SEE DEMO HERE
HTML code is
<input id="txtId" type="text" onkeyup="NumAndTwoDecimals(event , this);"></input>
To restrict user to enter only two number after '.' operator use
function NumAndTwoDecimals(e , field) {
var val = field.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
field.value = val[0];
} else {
field.value = "";
}
}
}
SEE DEMO HERE
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Help, I am trying to validate my form. It can validate all fields, but not submitting after validated. I tried to run the codes in http://jsfiddle.net/CrLsR/297/ but after validated the form, it can't proceed to the test.html page. I'm new in javascript so, I can't figure out what is the probleml. Any help will very much appreciated. thanks..
here is the code :
//HTML FORM
<form name="form" id="form" onsubmit="return (validateForm(this));" action="test.htm" method="post">
<label for="firstname" id="errfName">First Name</label>
<li><input name="firstname" type="text" onkeyup="return(validatefName(this));"> <span id="warnfName"></span></li>
<label for="username" id="errUser">Username</label>
<li><input name="username" type="text" onkeyup="return(validateUsername(this));"> <span id="warnUser"></span></li>
<label for="password" id="errPass">Password</label></li>
<li><input name="password" id="password" type="password" onkeyup="return(validatePassword(this));"> <span id="warnPass"></span></li>
<label for="password2" id="errPass2">Confirm Password</label></li>
<li><input name="password2" id="password2" type="password" onkeyup="return(validatePassword2(this));"> <span id="warnPass2"></span></li>
<label for="email" id="errEmail">Email Address</label>
<li><input name="email" type="text" onkeyup="return(validateEmail(this));"> <span id="warnEmail"></span></li>
<li> </td>
<li><input name="Submit" value="Send" type="submit" ></li>
// Javascript code
var borderErr = "1px solid rgb(100,0,50)";
var borderOk = "1px solid rgb(0,150,50)";
var warn = "<b class='warn'>!</b>";
// for First Name validation
var matchfName = /^[a-zA-Z]$/;
var errorfNameEmpty = "<b class='err'>First name is required";
// for Username validation
var matchUsername = /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/;
var matchUsername2 = /^[a-z0-9_-]{5,15}$/;
var errorUsernameEmpty = "<b class='err'>Username is required\n</b>";
var errorUsernameInvalid = "<b class='err'>The username is not valid. Must contains 5 to 15 alpha numeric characters\n</b>";
// for Password validation
var matchPass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{7,15}$/;
var errPassEmpty = "<b class='err'>Password is required</b>";
var errPassInvalid = "<b class='err'>Password must contains with a combination of <br/>7 to 15 alpha numeric and special characters.";
// for Confirm Password validation
var errPassEmpty2 = "<b class='err'>Confirm password is required</b>";
var errPassInvalid2 = "<b class='err'>Confirm password must the same as password value.";
// for Email validation
var matchEmail = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var errEmailEmpty = "<b class='err'>Email address is required</b>";
var errEmailInvalid = "<b class='err'>Invalid email address. Please enter a valid email.";
function validateForm(regForm) {
var warning = "";
warning += validatefName(regForm.firstname);
warning += validateUsername(regForm.username);
warning += validatePassword(regForm.password);
warning += validatePassword2(regForm.password2);
warning += validateEmail(regForm.email);
if (warning != "") {
return false;
}
return true;
}
// validate first name
function validatefName(fld) {
if(fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errfName").innerHTML=errorfNameEmpty;
document.getElementById("warnfName").innerHTML=warn;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errfName").innerHTML="First Name";
document.getElementById("warnfName").innerHTML="";
return true;
}
}
//validate username
function validateUsername(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errUser").innerHTML=errorUsernameEmpty;
document.getElementById("warnUser").innerHTML=warn;
return false;
}
else if ((!matchUsername.test(fld.value)) || (!matchUsername2.test(fld.value))) {
fld.style.border=borderErr;
document.getElementById("errUser").innerHTML=errorUsernameInvalid;
document.getElementById("warnUser").innerHTML=warn;
return false;
}
else {
document.getElementById("errUser").innerHTML="Username";
document.getElementById("warnUser").innerHTML="";
fld.style.border=borderOk;
return true;
}
}
// validate password
function validatePassword(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errPass").innerHTML=errPassEmpty;
document.getElementById("warnPass").innerHTML=warn;
return false;
}
else if (!matchPass.test(fld.value)) {
document.getElementById("errPass").innerHTML=errPassInvalid;
document.getElementById("warnPass").innerHTML=warn;
fld.style.border=borderErr;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errPass").innerHTML="Password";
document.getElementById("warnPass").innerHTML="";
return true;
}
}
// validate confirm password
function validatePassword2(fld) {
var passVal = document.getElementById("password").value;
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errPass2").innerHTML=errPassEmpty2;
document.getElementById("warnPass2").innerHTML=warn;
return false;
}
else if (passVal != fld.value) {
document.getElementById("errPass2").innerHTML=errPassInvalid2;
document.getElementById("warnPass2").innerHTML=warn;
fld.style.border=borderErr;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errPass2").innerHTML="Confirm Password";
document.getElementById("warnPass2").innerHTML="";
return true;
}
}
// validate email address
function validateEmail(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errEmail").innerHTML=errEmailEmpty;
document.getElementById("warnEmail").innerHTML=warn;
return false;
}
else if (!matchEmail.test(fld.value)) {
fld.style.border=borderErr;
document.getElementById("errEmail").innerHTML=errEmailInvalid;
document.getElementById("warnEmail").innerHTML=warn;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errEmail").innerHTML="Email Address";
document.getElementById("warnEmail").innerHTML="";
return true;
}
}
As your inner validation methods return true or false, you need to modify your parent validation method to this or similar.
function validateForm(regForm) {
var formValid = true;
formValid &= validatefName(regForm.firstname);
formValid &= validateUsername(regForm.username);
formValid &= validatePassword(regForm.password);
formValid &= validatePassword2(regForm.password2);
formValid &= validateEmail(regForm.email);
if (!formValid) {
return false;
}
return true;
}
Try changing this line
var warning = "";
warning += validatefName(regForm.firstname);
warning += validateUsername(regForm.username);
warning += validatePassword(regForm.password);
warning += validatePassword2(regForm.password2);
warning += validateEmail(regForm.email);
if (warning != "") {
To this line
if(validatefName(regForm.firstname) == true && validateUsername(regForm.username) == true && validatePassword(regForm.password) == true && validatePassword2(regForm.password2) == true && validateEmail(regForm.email) == true) {
and see if it is correct now
Based on your fiddle, I found some errors in your code in the condition
if (title=="" || title==null) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
}
Should be
if (title.length != 0) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}
The second is a more effective way to check if a field has no value.
I've also added return false in your else condition and the last return should be true.
here is your validateForm function. I updated your fiddle here
function validateForm() {
// Validate Email
var email = $("#fremail").val();
if ((/(.+)#(.+){2,}\.(.+){2,}/.test(email)) || email.length != 0) {
} else {
alert("Please enter a valid email");
return false;
}
// Validate Title
var title = $("#frtitle").val();
if (title.length != 0) {} else {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) {} else {
alert("Please enter a valid URL, remember including http://");
return false;
}
return true;
}
Set a Flag = 1 in the function validateForm()
Increment Flag, if have validation error
End, return true, if Flag == 1 which means no error
function validateForm()
{
var flag = 1;
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
flag++;
}
// Validate Title
var title = $("#frtitle").val();
if (title=="" || title==null) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
flag++;
}
// Validate Email
var email = $("#fremail").val();
if ((/(.+)#(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
alert("Please enter a valid email");
flag++;
}
if (flag == 1)
return true;
else
return false;
}
http://jsfiddle.net/3vHxF/ Here is what I tried
And my html code is :
<form id="commentForm" style="width:200px;" name="MYFORM" action="#">
<label>
<strong>Enquiry Form </strong>
</label>
<label>Name</label>
<input id="name" type="text" size="30" name="name">
<label>Phone No</label>
<input id="phone" type="text" size="30" name="phone">
<label>Email</label>
<input id="email" type="text"size="30" name="email">
<label>Message</label><br>
<textarea id="message" name="message"></textarea>
<input id="Send" type="submit" value="Send" onclick="send()">
</form>
Javascript is :
var name=getElementById('name');
var phone=getElementById('phone');
var email=getElementById('email');
var mess=getElementById('message');
function send(){
if(name==null&&phone==null&&email==null&&mess==null)
alert('field is empty');
}
I want to alert the field which is empty, and at the same time I want to write it simply. Please don't suggest any plug-ins.
Remove the click handler from the button and put a submit handler on the form:
<form id="commentForm" onsubmit="return validat(this);" ... >
Now you can do a simple validation:
function validate(form) {
var control;
var isValid = true;
for (var i=0, iLen=form.elements.length; i<iLen; i++) {
control = form.elements[i];
if (control.value == '') {
alert('Field ' + control.name + ' is empty');
isValid = false;
}
}
return isValid; // false cancels submit
}
That is a very minimal validation script, but it's a start.
Incidentally, since your form controls have names (which are required to be successful), they don't need ids.
Your problems:
You are testing HTMLInputElement objects and not the values they hold (so get the value)
You are comparing strings to null (compare to an empty string)
Your failure condition is based on all of them failing instead of any of them failing (use or not and)
Such:
if(name.value === "" || phone.value === "" || email.value === "" || mess.value === "")
alert('field is empty');
}
To determine which one is empty, you need to test them one at a time instead of in a single if statement with ||s.
Not a clean approach. But try developing the below code.
var name=document.getElementById('name').value;
var phone=document.getElementById('phone').value;
var email=document.getElementById('email').value;
var mess=document.getElementById('message').value;
function send(){
if(isEmpty(name, 'name') || isEmpty(phone, 'phone') || isEmpty(email, 'email') || isEmpty(mess, 'message')) {
return false;
}
return true;
}
function isEmpty(val, fld) {
if(val && val != null) {
return true;
}
alert(fld +" is Empty");
return false;
}
change
var name=getElementById('name');
var phone=getElementById('phone');
var email=getElementById('email');
var mess=getElementById('message');
to
var name=document.getElementById('name').value;
var phone=document.getElementById('phone').value;
var email=document.getElementById('email').value;
var mess=document.getElementById('message').value;
and then use
if(name.value === "" || phone.value === "" || email.value === "" || mess.value === "")
alert('field is empty');
}
You could use the following jQuery:
$(":text,textarea").each(function() {
$(this).css("outline", $(this).val() ? "1px solid red" : "none");
});
Sorry, I thought "no plugins" meant "no jQuery plugins." (You would call jQuery a library or dependency, not a "plugin")
This is a mostly untested non-jQuery version:
function highlightMissingInputs() {
for (var formIndex = 0; formIndex < document.forms.length; formIndex++) {
var form = document.forms[formIndex];
for (var inputIndex = 0; inputIndex < form.length; inputIndex++) {
var input = form[inputIndex];
switch (input.tagName) {
case "INPUT":
var typeAttribute = input.attributes.type;
if (typeAttribute) {
var type = (typeAttribute.value || "").toLowerCase();
switch (type) {
case undefined:
case "":
case "text":
case "email":
case "tel":
case "email":
case "search":
break;
default:
continue;
}
}
break;
case "TEXTAREA":
break;
default:
continue;
}
input.style.outline = input.value ? "none" : "1px solid red";
}
}
}