How can I check if a input field is empty in JavaScript when submitting the form?
html:
<input type="text" name="start_name" id="start_name">
Refer to http://www.w3schools.com/js/js_form_validation.asp
Have your form tag as
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Next, have a javascript function
<script>
function validateForm()
{
var x=document.forms["myForm"]["start_name"].value;
if (x==null || x=="")
{
alert("Start name must be filled out");
return false;
}
}
</script>
var start_name = document.getElementById('start_name');
if( start_name.value.length > 0 ){
// Then there is something there.
}
Try.
<script type="text/javascript">
function checkme()
{
var inputVal = document.getElementById("start_name").value;
if(inputVal == "")
{
//code
}
}
</script>
<form action="" method="post" onSubmit = "checkme();">
<input type="text" name="start_name" id="start_name">
</form>
Just checking 'if (x==null || x=="")' is not enough to validate empty text box. Go for RegEx to check empty text box.
/^\s*[0-9a-zA-Z][0-9a-zA-Z ]*$/
Ensures that at least one character is not whitespace and is of one of the allowed characters.
Use /[a-z]/i as this regex will only match if there is at least one alphabetical character.
<form action="someActionUrl" onsubmit="return validate('first_name')">
<input id="first_name" name="first_name" />
</form>
<script>
function validate(inputId){
var val = document.getElementById(inputId).value;
if(val.length>0){
// do something
return true;
}
return false;
}
</script>
try this:
var x = document.getElementById("start_name");
if(x.value== "")
{
//your restriction code comes here
}
else
{
//go ahead!
}
Note: please check for syntax if its proper.i am writing the code here directly,haven't checked it on IDE.
Related
Okay so I know this is probably a headache for most of you but i'm having trouble figuring this out as javascript is not my strong suit.
I'm trying to basically get this one page to load if username and password is not blank but if it is blank I want it to alert to me (specifically window.alert()) that I have not inputted username and/or password.
I cannot seem to figure it out so here it is.
<button type="submit" id="enterButton" onclick="newPage()"><strong>Enter</strong></button>
there is my button where I put my function on
var username = getElementById("userName");
var password = getElementById("passWord");
function newPage() {
if(username.val().length==0 || password.val().length==0){
alert("please enter valid information");
return location.href = "newPage.html";
}
else{
location.href = "newPage.html";
}
}
and here is my failed attempt to initialize my idea.
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if (password==null || password==""){
alert("password can't be blank");
return false;
} else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<html>
<body>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Try to check first if you can get the value of your username. If you're using plain javascript, you should use document.getElementById("userName").value.
How can I prevent submision if in my text field are entered just specific characters <>{} and not all of special characters? I'm losing my mind :/
I think you are looking for regex expression. Let me know if it's helpful
$(":input").each(function() {
var input = $(this).val();
var regex = new RegExp("^[a-zA-Z]+$");
if(regex.test(input)) {
alert("true");
} else {
alert("false");
return false;
}
})
I don't have an exact answer as you didn't post any sample code. I can only point you to this article https://javascript.info/bubbling-and-capturing which explain how events bubbling works. A solution will be to use event.stopPropagation() in case the validation doesn't pass.
Here an working ex:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
const regex = new RegExp('^[a-zA-Z]+$');
const input = document.forms['someForm']['somename'].value;
if (regex.test(input)) {
console.log("true");
} else {
console.log("false");
return false;
}
}
</script>
</head>
<body>
<form name="someForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="somename">
<input type="submit" value="Submit">
</form>
</body>
</html>
I have a very strange problem. Inside form I have hidden input with value -1 and input field for username.
<form action="" method="POST" name="login" onSubmit="return Validate()">
<input type="text" id="username"/>
<input type="hidden" id="available" value="-1"/>
< input type="submit" value="Send"/>
</form>
On submit function Validate() checks value of username input which mustn't be empty, and Validate() also checks value of available input which mustn't be valued -1.
function Validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else if(b<0)
{
alert("Form isn't finished");
return false;
}
else
{
return true;
}
}
Problem is that Validate() works only if one condition is evalueted. If function Validate() contains only 1 var(a or b) and 1 if order(without else if) it works correctly. But when I put it like this, when Validate uses a and b variables and if, else if conditional order it won't work. Really od.. Thanks in advance...
In this case it works:
function Validate(){
var a=document.getElementById("username").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else
{
return true;
}
}
<input type="hidden" id="available" value="-1"/>
Here the value is of string dataType. Whereas
else if(b<0) //b is string dataType
Hence it failed. so change it as
var b= Number(document.getElementById("available").value);
Try like this
HTML:
<form action="" method="POST" name="login">
<input type="text" id="username" />
<input type="hidden" id="available" value="1" />
<input type="button" value="Send" onClick="return Validate()" />
</form>
JS:
function Validate() {
var a = document.getElementById("username").value;
var b = Number(document.getElementById("available").value);
if (a == "" || a == null) {
alert("Username cannot be empty");
return false;
} else if (b < 0) {
alert("Form isn't finished");
return false;
} else {
document.login.submit(); //dynamically submit the form
}
}
If you are wanting to get error notifications for each input don't use if/else here, use multiple if's and set your errors
function validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
var errors = [];
if(a=="" || a==null){
errors.push("Invalid username");
}
if(b<0 || isNaN(b)){
errors.push("Invalid available value");
}
if(errors.length>0) {
//do something with errors (like display them
return false;
}
}
Using the else if one of them evaluates to true it will skip the others. For instance if the first one is empty or null then it will do that block and skip the others.
I was testing your code for IE and Firefox and it work. Just add parseInt when you get the value of var b.
var b= parseInt(document.getElementById("available").value);
I want that Name field should contain text only.
<html>
<head></head>
<body>
<form name="form1">
Name <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Can anyone tell me how can I do so using either HTML or Javascript.
Use this regex in your Javascript: /^[a-z]+$/i
WORKING DEMO
Javascript:
var submit = document.getElementById("submit");
submit.addEventListener("click", checkInput, false);
function checkInput(e){
e.preventDefault();
var pattern = /^[a-z]+$/i;
alert(pattern.test(document.getElementById('text').value));
}
You can test whether there's "anything left" after removing alpha characters.
<html>
<body>
<form name="form1" onsubmit="return checkform();">
Name<input type="text" name="fname" id="fname">
<input type="submit" value="Submit">
</form>
<script>
function checkform(){
var fname=document.getElementById('fname').value;
if (fname.replace(/\w/g,'')!=''||fname==''){
alert('invalid firstname!');
return false;
}
return true;
}
</script>
</body>
</html>
try this:
<script type="text/javascript">
function validate(){
var allowedChars="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var n=form1.fname.value;
for(var i=0;i<n.length;i++){
if(allowedChars.indexOf(n.charAt(i))==-1){
return false; // contains other char
}
}
return true; //valid name
}
Try regular expressions like
var match_text = /[a-zA-Z]/;
try this var regx = /^[A-Za-z][-a-zA-Z ]+$/;
function validate_form();
{
var regx = /^[A-Za-z][-a-zA-Z ]+$/;
var fname = document.getElementById('fname').value;
if(fname=="")
{
alert("Name is Blank");
return false;
}
else if(!regx.test(fname))
{
alert("name must contains character only");
return false;
}
else
{
return true;
}
}
Pattern checking of the textbox must be done with Javascript or Jquery like in other answers BUT if you want to use HTML5, you can directly write :
<input type="text" name="fname" id="fname" pattern="[A-Za-z]+" />
(See 'pattern' attribute in HTML5 if you're interested).
You can call this function to validate input field containing only text--
function validate()
{
str = document.form1.fname.value;
var patt = new RegExp("^[a-zA-Z ]*$");
var res = patt.test(str);
if(!res)
{
alert("do not match!");
return false;
}
}
I am trying to use JavaScript to validate forms but if the form doesn't validate, I don't want the form to be sent to the "action" page.
The validator:
<script>
function formSubmit()
{
document.getElementById("signup_form").submit();
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
The form itself:
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
But all this does is if the tname field empty, it will return an alert but as soon as the user hits ok, the form then redirects to some_file.php. What have I missed here?
The submit button:
Signup
So what have I missed? How do I avoid this in the future?
You have the wrong execution of statememts. You are submitting the form before validating. Move this statement below the if statement
document.getElementById("signup_form").submit();
further to this. you are calling formSubmit() at two places, form tag and a tag doing it once is fine.
UPDATED CODE:
<html>
<head>
<title></title>
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
document.getElementById("signup_form").submit();
}
</script>
</head>
<body>
<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">
<input type="text" name="tname" />
Signup
</body>
</html>
DEMO
Try this:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
*Changes made to your code: *
- There is no need for formSubmit to try to submit the form! Just perform the validation checks and return true if you want the submission to proceed or false otherwise.
Also you do not need to check for the x == null case. If the textbox is empty, its value will be "".
What might be needed though is a check that x does not just contain spaces. If you do not care about supporting older browsers you can use the new Javascript trim function. If you care about backwards compatibility, either try one of the many javascript libraries that offer trim or the following:
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value.replace(/^\s+|\s+$/g, '');
if (x=="")
{
alert("First name must be filled out");
return false;
}
return true;
}
If I just wanted to avoid submitting spaces I would have left the var x= bit as it was and added the replace in the check making it if(x.replace(/\s/g, '') == ""). However, I also want to trim the input so that if the user enters " user1" or "user1 " the form will send "user1".
You can see the three different versions versions working here:
http://jsfiddle.net/9LPfb/2/
http://jsfiddle.net/9LPfb/3/
http://jsfiddle.net/9LPfb/6/
you have problem with your program flow .
do validation before the submitting form.
there is no use of validating after submitting, i think you have mistakenly made it.
just submit after validation.
try:
function formSubmit() {
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else {
return true;
}
}
You already had all the code. It was becos of wrong execution.
<script>
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (!x){
alert("First name must be filled out");
return false;
}
return true;
}
</script>
<form action="some_file.php" method="post" id="signup_form" name="signup_form">
Signup
in your function just remove this line
document.getElementById("signup_form").submit();
and add it after the if condition
or rewrite the function like the one below
function formSubmit()
{
var x=document.forms["signup_form"]["tname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}else
return true;
}
Contact Form
function empty() {
var x,y;
x = document.forms["ff"]"name"].value;
y = document.forms["ff"]["surname"].value;
if(x=="" ||x==null){
alert("Enter your name");
return false;
}else if(y==""){
alert("Enter your surname");
return false;
}else{
alert('Data is sending');
return true;
}
};
In the html:
<form method="POST" action="formdata.php" name="ff"onsubmit="return empty()">
<table>
<tr>
<td>Enter Your Name : <input type="text" name="name" maxlength="30" size="40" id="na" ></td>
</tr>
<tr>
<td>Enter Your Surname : <input type="text" name="surname" maxlength="30" size="40" id="sna"></td>
</tr>
<tr>
<td>
<input type="submit" name="formsubmit" value="submit" >
</td>
</tr>
</table>
</form>