简体   繁体   中英

Prevent form submit when the javascript is disabled

I have a mvc form with client side validations.

I want to make sure users cant submit the page if the javascript is disabled because then the validations will be bypassed. Is this possible, how can it be done?

Thanks in advance!

Although maybe possible, this is not a good way to solve your problem. Client side validation is no replacement for server side checks. You must do server side checks anyway, because nobody is forcing users to use your frontend at all. They could build their own webpage to submit data to your application.

EDIT: Similar to sitnarf

Make it by default not display:

<input type="submit" id="submitButton" value="Submit" style="display:none;"/>

Notice the display: none;

Then in javascript you can do:

document.getElementById("submitButton").style.display = 'inline-block';

Which makes it visible again ( inline-block is the normal display type of submit buttons).

Remember to put the javascript code at the bottom of you're body tag or wrap it in a function similar to document.onload to make sure it doesn't get the element till the page has been loaded

Example http://jsfiddle.net/74555/

You could always use Javascript to submit the form, using a button called Submit which isn't a submit button!

HTML

<input type="button" name="Submit" value="Submit" onclick="SubmitForm()">

JS

function SubmitForm()
{
    document.getElementById("myForm").submit();
}

With javascript disabled, clicking the button won't do anything.

Default state has to be, that form can't be submitted (don't use action attribute), eg

<div class='error'>Turn your javascript to active form</div>
<form>   
...
Field: <input type="text" name="name">
<input type="submit" style="display: none">
</form>

And with javascript, append tag behind to hide message and show submit button:

<script>
    $(".error").hide();
    $("submit").show();   
    $("form").attr("action", "someurl.php");  
</script>

In asp.net mvc there is also a good feature ModelState.IsValid to check whether model validation has satisfied or not you can use that if somehow javascript is disabled in browser or somehow client validations bypassed..

public ActionResult Index()
 {
     if( ModelState.IsValid )
     {}
     else
     {}
 }

Always try to use ModelState.IsValid in asp.net mvc because client validations are never reliable and also there is no full proof way to check whether javascript is enabled or disabled..the advantage of using ModelState.IsValid is that if whether javascript is enabled or disabled your form will submit and all validations for model will be checked on controller side also..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM