简体   繁体   中英

HTML form required field

I have an HTML form in Rails like

<form name="input">
  Title: <input type="text" name="title"> 
  <input type="button" value="Submit">
</form> 

I want title to be a required field (ie the user cannot leave it blank.) How can I verify that the user filled something in? Should I do it on the client side, or on the server side? My feeling is that doing on the client side would save communication to the server in the case that the user didn't fill it in.

You can do both, but should at least do it on the server. Remember that any client can easily circumvent any client-side validation, which leads to your code potentially breaking.

You can do it easily in the model with:

validates_presence_of :title

On the client there are various ways of how to do this. The simplest is perhaps using the required html5 attribute on the input tag. You can also use a javascript library like validatious , for which you can use this Rails plugin to automatically generate the client side validations based on your server-side validations.

If you want to be really on the safe side, you HAVE to do it on the server anyways. The client side validation is only for the sake of convenience.

You should do it on the client because it's more convenient to the user (a better user experience).

And, do it on the server in case client-side validation fails (because JavaScript is turned off, or there's a bug in client-side code, or an unsupported browser, or a malicious cracker trying to send garbage to your server, etc.).

Do validation on client side and server side..

Client side validation is not safe and can disbaled..,

Server side validation have to be performed and can not bypass

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