SlideShare a Scribd company logo
CS142 Lecture Notes - Input
Input and Validation
Mendel Rosenblum
CS142 Lecture Notes - Input
Early web app input: HTTP form tag
<form action="/product/update" method="post">
Product: <input type="text" name="product"/><br />
Deluxe: <input type="checkbox" name="delux" /><br />
<input type="submit" value="Submit"/>
</form>
● method="get" - Encode form properties as query params
HTTP GET product/update?product=foobar&delux=on
● method="post" - Encode form properties as query params in message body
HTTP POST product/update
Content-Type: application/x-www-form-urlencoded
product=foobar&delux=on
CS142 Lecture Notes - Input
Rails input pattern using form POST
● GET Page containing form
○ Contains a method="post" form to a POST Page
● POST Page - Validate and perform operation (typically create or update)
○ If successful, redirect to a "done "page (possibly another GET Page) if successful
○ If failed validation, redirect page to the GET Page with incorrect fields highlighted
○ If error, redirect to some oops page
CS142 Lecture Notes - Input
Validation requirements in web applications
● Protect integrity of storage (required fields, organization, security, etc.)
○ Can not let HTTP request either from web app or generated out the web app damage us
○ Need to enforce at web server API
● Provide a good user experience
○ Don't let users make mistakes or warn them as soon as possible
○ Pushing validation closer to the user is helpful
● Validation in JavaScript frameworks (ReactJS)
○ Rule #1: Still need server-side validation to protect storage system integrity
○ Rule #2: Let user know about validity problems as early as possible
CS142 Lecture Notes - Input
Input in ReactJS: familiar HTML form/input model
● ReactJS uses HTML form elements: <input>, <textarea>, and <select>
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name: <input type="text" value={this.state.inputValue} onChange={this.handleChangeInput} />
</label>
<label>
Essay: <textarea value={this.state.textValue} onChange={this.handleChangeText} />
</label>
<label>
Pick<select value={this.state.selValue} onChange={this.handleChangeSelect}>
<option value="yes">Yes</option>
<option value="no">No</option>
<option value="maybe">Maybe</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
CS142 Lecture Notes - Input
Input in ReactJS handling events
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value}); // Common approach to push into component state
}
handleSubmit(event) {
// Process submit from this.state
event.preventDefault(); // Need to stop DOM from generating a POST
}
CS142 Lecture Notes - Input
JSX and this handling - No ideal way
● Specifying a method as DOM event callback doesn't work:
<form onSubmit={this.formSubmit}> … // Wrong! Calls with this undefined
● Arrow function embedded in JSX render: Can call instance method
<form onSubmit={event => this.formSubmit(event)}> …
● Redefine method function in instance to have correct this in constructor:
this.formSubmit = this.formSubmit.bind(this); // In component constructor
● Use new JavaScript class fields: class Foo { fieldName = value;
CS142 Lecture Notes - Input
Validation in ReactJS
● Unopinionated! Lots of different packages
○ Example: Formik - Build forms in React, without tears.
○ Handles specifying form, validation methods, form error reporting, etc.
● Flexible: Can do validation anyway you want
handleChange(event) {
if (this.validateIt(event.target.value, this.state) {
this.setState({renderValidationError: true});
}
this.setState({value: event.target.value});
}
Arbitrary JavaScript can look at
event.target.value and this.state and use
setState causing render() be called again.
CS142 Lecture Notes - Input
Asynchronous validation
● Can in background communicate with web server to validate input
○ Example: username already taken
● Example: Autocomplete with React-AutoSuggest
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
● Trend towards using recommendation systems for input guidance
CS142 Lecture Notes - Input
Single Page App Input
● Rather than POST with redirect you can do a XMLHttpRequest POST/PUT
● React: Unopinionated - Many options to choose from.
○ Example: Axios - Promise based HTTP client for the browser and node.js
axios.get(url)
axios.delete(url)
axios.post(url, body)
axios.put(url, body)
CS142 Lecture Notes - Input
Axios Model fetch
axios.get(URLpath)
.then((response) => {
// response.status - HTTP response status (eg 200)
// response.statusText - HTTP response status text (eg OK)
// response.data - Response body object (JSON parsed)
})
.catch((err) => {
// err.response.{status, data, headers) - Non-2xx status HTTP response
// if !err.response - No reply, can look at err.request
});
CS142 Lecture Notes - Input
Axios Model fetch - Alternative Error Handling
axios.get(URLpath)
.then((response) => {
// response.status - HTTP response status (eg 200)
// response.statusText - HTTP response status text (eg OK)
// response.data - Response body object (JSON parsed)
},
(err) => {
// err.response.{status, data, headers) - Non-2xx status HTTP response
// if !err.response - No reply, can look at err.request
});
CS142 Lecture Notes - Input
Axios Model uploading
axios.post(URLpath, objectWithParameters)
.then((response) => {
// response.status - HTTP response status (eg 200)
// response.statusText - HTTP response status text (eg OK)
// response.data - Response body object (JSON parsed)
})
.catch((err) => {
// err.response.{status, data, headers) - Non-2xx status HTTP response
// if !err.response - No reply, can look at err.request
});
CS142 Lecture Notes - Input
Server-side validation
● Regardless of validation in browser server needs to check everything
○ Easy to directly access server API bypassing all browser validation checks
● Mongoose allows validator functions
var userSchema = new Schema({
phone: { type: String,
validate: {
validator: function(v) {
return /d{3}-d{3}-d{4}/.test(v);
},
message: '{VALUE} is not a valid phone number!'
}
}
});
CS142 Lecture Notes - Input
Some integrity enforcement requires special code
● Maintaining relationship between objects
● Resource quotas
● Examples related to our Photo App
○ Only author and admin user can delete a photo comment.
○ A user can only upload 50 photos unless they have a premium account.

More Related Content

Similar to Input.pdf

ReactJS.pdf
ReactJS.pdfReactJS.pdf
ReactJS.pdf
IbrahimRashidBayoh
 
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 Connecting Content Silos: One CMS, Many Sites With The WordPress REST API Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
Caldera Labs
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
Martin Kleppe
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
Dongho Cho
 
Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發
HO-HSUN LIN
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
React 101
React 101React 101
React 101
Casear Chu
 
Gutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesGutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisables
Riad Benguella
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
Nitish Phanse
 
Taming forms with React
Taming forms with ReactTaming forms with React
Taming forms with React
GreeceJS
 
Advanced redux
Advanced reduxAdvanced redux
Advanced redux
Boris Dinkevich
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab Academy
DreamLab
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React Performance
Ching Ting Wu
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh Pollock
Caldera Labs
 
05 communications
05 communications05 communications
05 communications
memeapps
 
Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2
Ahmed Moawad
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
Bernd Alter
 
React и redux
React и reduxReact и redux
Chekout demistified
Chekout demistifiedChekout demistified
Chekout demistified
Damijan Ćavar
 
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
Rob Tweed
 

Similar to Input.pdf (20)

ReactJS.pdf
ReactJS.pdfReactJS.pdf
ReactJS.pdf
 
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 Connecting Content Silos: One CMS, Many Sites With The WordPress REST API Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發Chaincode Development 區塊鏈鏈碼開發
Chaincode Development 區塊鏈鏈碼開發
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
React 101
React 101React 101
React 101
 
Gutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisablesGutenberg sous le capot, modules réutilisables
Gutenberg sous le capot, modules réutilisables
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
Taming forms with React
Taming forms with ReactTaming forms with React
Taming forms with React
 
Advanced redux
Advanced reduxAdvanced redux
Advanced redux
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab Academy
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React Performance
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh Pollock
 
05 communications
05 communications05 communications
05 communications
 
Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
 
React и redux
React и reduxReact и redux
React и redux
 
Chekout demistified
Chekout demistifiedChekout demistified
Chekout demistified
 
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
 

More from stephanedjeukam1

HTTP.pdf
HTTP.pdfHTTP.pdf
Database.pdf
Database.pdfDatabase.pdf
Database.pdf
stephanedjeukam1
 
HTML.pdf
HTML.pdfHTML.pdf
CodeInjection.pdf
CodeInjection.pdfCodeInjection.pdf
CodeInjection.pdf
stephanedjeukam1
 
FrontEnd.pdf
FrontEnd.pdfFrontEnd.pdf
FrontEnd.pdf
stephanedjeukam1
 
DOM.pdf
DOM.pdfDOM.pdf
CSS.pdf
CSS.pdfCSS.pdf
DOSAttacks.pdf
DOSAttacks.pdfDOSAttacks.pdf
DOSAttacks.pdf
stephanedjeukam1
 
0000 Syllabus.pdf
0000  Syllabus.pdf0000  Syllabus.pdf
0000 Syllabus.pdf
stephanedjeukam1
 
Events.pdf
Events.pdfEvents.pdf
Events.pdf
stephanedjeukam1
 

More from stephanedjeukam1 (10)

HTTP.pdf
HTTP.pdfHTTP.pdf
HTTP.pdf
 
Database.pdf
Database.pdfDatabase.pdf
Database.pdf
 
HTML.pdf
HTML.pdfHTML.pdf
HTML.pdf
 
CodeInjection.pdf
CodeInjection.pdfCodeInjection.pdf
CodeInjection.pdf
 
FrontEnd.pdf
FrontEnd.pdfFrontEnd.pdf
FrontEnd.pdf
 
DOM.pdf
DOM.pdfDOM.pdf
DOM.pdf
 
CSS.pdf
CSS.pdfCSS.pdf
CSS.pdf
 
DOSAttacks.pdf
DOSAttacks.pdfDOSAttacks.pdf
DOSAttacks.pdf
 
0000 Syllabus.pdf
0000  Syllabus.pdf0000  Syllabus.pdf
0000 Syllabus.pdf
 
Events.pdf
Events.pdfEvents.pdf
Events.pdf
 

Recently uploaded

Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
APNIC
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
xjq03c34
 
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
thezot
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
3a0sd7z3
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
Donato Onofri
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
davidjhones387
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
APNIC
 
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
rtunex8r
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
k4ncd0z
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
Paul Walk
 
Bengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal BrandingBengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal Branding
Tarandeep Singh
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
3a0sd7z3
 

Recently uploaded (12)

Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
 
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
 
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
 
Bengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal BrandingBengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal Branding
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
 

Input.pdf

  • 1. CS142 Lecture Notes - Input Input and Validation Mendel Rosenblum
  • 2. CS142 Lecture Notes - Input Early web app input: HTTP form tag <form action="/product/update" method="post"> Product: <input type="text" name="product"/><br /> Deluxe: <input type="checkbox" name="delux" /><br /> <input type="submit" value="Submit"/> </form> ● method="get" - Encode form properties as query params HTTP GET product/update?product=foobar&delux=on ● method="post" - Encode form properties as query params in message body HTTP POST product/update Content-Type: application/x-www-form-urlencoded product=foobar&delux=on
  • 3. CS142 Lecture Notes - Input Rails input pattern using form POST ● GET Page containing form ○ Contains a method="post" form to a POST Page ● POST Page - Validate and perform operation (typically create or update) ○ If successful, redirect to a "done "page (possibly another GET Page) if successful ○ If failed validation, redirect page to the GET Page with incorrect fields highlighted ○ If error, redirect to some oops page
  • 4. CS142 Lecture Notes - Input Validation requirements in web applications ● Protect integrity of storage (required fields, organization, security, etc.) ○ Can not let HTTP request either from web app or generated out the web app damage us ○ Need to enforce at web server API ● Provide a good user experience ○ Don't let users make mistakes or warn them as soon as possible ○ Pushing validation closer to the user is helpful ● Validation in JavaScript frameworks (ReactJS) ○ Rule #1: Still need server-side validation to protect storage system integrity ○ Rule #2: Let user know about validity problems as early as possible
  • 5. CS142 Lecture Notes - Input Input in ReactJS: familiar HTML form/input model ● ReactJS uses HTML form elements: <input>, <textarea>, and <select> render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.inputValue} onChange={this.handleChangeInput} /> </label> <label> Essay: <textarea value={this.state.textValue} onChange={this.handleChangeText} /> </label> <label> Pick<select value={this.state.selValue} onChange={this.handleChangeSelect}> <option value="yes">Yes</option> <option value="no">No</option> <option value="maybe">Maybe</option> </select> </label> <input type="submit" value="Submit" /> </form> ); }
  • 6. CS142 Lecture Notes - Input Input in ReactJS handling events class MyForm extends React.Component { constructor(props) { super(props); this.state = { }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); // Common approach to push into component state } handleSubmit(event) { // Process submit from this.state event.preventDefault(); // Need to stop DOM from generating a POST }
  • 7. CS142 Lecture Notes - Input JSX and this handling - No ideal way ● Specifying a method as DOM event callback doesn't work: <form onSubmit={this.formSubmit}> … // Wrong! Calls with this undefined ● Arrow function embedded in JSX render: Can call instance method <form onSubmit={event => this.formSubmit(event)}> … ● Redefine method function in instance to have correct this in constructor: this.formSubmit = this.formSubmit.bind(this); // In component constructor ● Use new JavaScript class fields: class Foo { fieldName = value;
  • 8. CS142 Lecture Notes - Input Validation in ReactJS ● Unopinionated! Lots of different packages ○ Example: Formik - Build forms in React, without tears. ○ Handles specifying form, validation methods, form error reporting, etc. ● Flexible: Can do validation anyway you want handleChange(event) { if (this.validateIt(event.target.value, this.state) { this.setState({renderValidationError: true}); } this.setState({value: event.target.value}); } Arbitrary JavaScript can look at event.target.value and this.state and use setState causing render() be called again.
  • 9. CS142 Lecture Notes - Input Asynchronous validation ● Can in background communicate with web server to validate input ○ Example: username already taken ● Example: Autocomplete with React-AutoSuggest <Autosuggest suggestions={suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} getSuggestionValue={getSuggestionValue} renderSuggestion={renderSuggestion} inputProps={inputProps} /> ● Trend towards using recommendation systems for input guidance
  • 10. CS142 Lecture Notes - Input Single Page App Input ● Rather than POST with redirect you can do a XMLHttpRequest POST/PUT ● React: Unopinionated - Many options to choose from. ○ Example: Axios - Promise based HTTP client for the browser and node.js axios.get(url) axios.delete(url) axios.post(url, body) axios.put(url, body)
  • 11. CS142 Lecture Notes - Input Axios Model fetch axios.get(URLpath) .then((response) => { // response.status - HTTP response status (eg 200) // response.statusText - HTTP response status text (eg OK) // response.data - Response body object (JSON parsed) }) .catch((err) => { // err.response.{status, data, headers) - Non-2xx status HTTP response // if !err.response - No reply, can look at err.request });
  • 12. CS142 Lecture Notes - Input Axios Model fetch - Alternative Error Handling axios.get(URLpath) .then((response) => { // response.status - HTTP response status (eg 200) // response.statusText - HTTP response status text (eg OK) // response.data - Response body object (JSON parsed) }, (err) => { // err.response.{status, data, headers) - Non-2xx status HTTP response // if !err.response - No reply, can look at err.request });
  • 13. CS142 Lecture Notes - Input Axios Model uploading axios.post(URLpath, objectWithParameters) .then((response) => { // response.status - HTTP response status (eg 200) // response.statusText - HTTP response status text (eg OK) // response.data - Response body object (JSON parsed) }) .catch((err) => { // err.response.{status, data, headers) - Non-2xx status HTTP response // if !err.response - No reply, can look at err.request });
  • 14. CS142 Lecture Notes - Input Server-side validation ● Regardless of validation in browser server needs to check everything ○ Easy to directly access server API bypassing all browser validation checks ● Mongoose allows validator functions var userSchema = new Schema({ phone: { type: String, validate: { validator: function(v) { return /d{3}-d{3}-d{4}/.test(v); }, message: '{VALUE} is not a valid phone number!' } } });
  • 15. CS142 Lecture Notes - Input Some integrity enforcement requires special code ● Maintaining relationship between objects ● Resource quotas ● Examples related to our Photo App ○ Only author and admin user can delete a photo comment. ○ A user can only upload 50 photos unless they have a premium account.